/**
 * Date: 2012-03-22 
 *
 * Copyright (C) 2011-2012 Jawa Software. 
 *
 */
package org.jawa.core.event;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import org.jawa.core.cache.ClusterTask;
import org.jawa.core.cache.ExternalizableUtil;
import org.jawa.core.util.JawaProperties;

/**
 * 此任务用于在本机属性发生变化时,更新或删除其它集群集节点的系统属性。
 */
public class PropertyClusterEventTask implements ClusterTask {

	private Type event;
	private String key;
	private String value;

	public static PropertyClusterEventTask createPutTask(String key, String value) {
		PropertyClusterEventTask task = new PropertyClusterEventTask();
		task.event = Type.put;
		task.key = key;
		task.value = value;
		return task;
	}

	public static PropertyClusterEventTask createDeteleTask(String key) {
		PropertyClusterEventTask task = new PropertyClusterEventTask();
		task.event = Type.deleted;
		task.key = key;
		return task;
	}

	public Object getResult() {
		return null;
	}

	public void run() {
		if (Type.put == event) {
			JawaProperties.getInstance().localPut(key, value);
		} else if (Type.deleted == event) {
			JawaProperties.getInstance().localRemove(key);
		}
	}

	public void writeExternal(ObjectOutput out) throws IOException {
		ExternalizableUtil.getInstance().writeInt(out, event.ordinal());
		ExternalizableUtil.getInstance().writeSafeUTF(out, key);
		ExternalizableUtil.getInstance().writeBoolean(out, value != null);
		if (value != null) {
			ExternalizableUtil.getInstance().writeSafeUTF(out, value);
		}
	}

	public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
		event = Type.values()[ExternalizableUtil.getInstance().readInt(in)];
		key = ExternalizableUtil.getInstance().readSafeUTF(in);
		if (ExternalizableUtil.getInstance().readBoolean(in)) {
			value = ExternalizableUtil.getInstance().readSafeUTF(in);
		}
	}

	private static enum Type {
		/**
		 * 创建或更新缓存.
		 */
		put,
		/**
		 * 删除缓存.
		 */
		deleted
	}
}
